﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.NetworkInformation;
using System.Xml;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json;
using Titan.Core;
using Titan.Core.Cryptography;
using Titan.DAS.Msg.Common;
using Titan.WinFormSys.Entity;
using Titan.DAS.Client.Data;
using log4net.Util;
//using Titan.FIS.BatchCodeEncode;

namespace Titan.WinFormSys
{
    /// <summary>
    /// 登陆窗体
    /// </summary>
    public sealed partial class FrmIndex : Form
    {
        private readonly string FilePath = Environment.CurrentDirectory + "\\UserInfo.dat";
        private string _url;
        private int _version;

        private string IP1 = "192.168.102.12", IP2 = "192.168.102.12";
        private int Port = 10100, TimeOut = 500;
        private bool _bIsOpen = false;

        private string _localIP = "172.0.0.1";
        private string _localMAC = "00:00:00:00:00:00";


        private bool _isNeedLogin = true;//是否需要真实登录数据库 

        /// <summary>
        /// 中间件地址
        /// </summary>
        private string Url
        {
            set
            {
                _url = value;
            }
            get
            {
                return _url;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmIndex()
        {
            InitializeComponent();
            DoInitUrl();

            _version = Convert.ToInt32(ConfigurationManager.AppSettings["Version"]);
            txt_UserAccout.Focus();
        }

        private void DoInitUrl()
        {
            try
            {
                IP1 = System.Configuration.ConfigurationManager.AppSettings["IP1"];
                IP2 = System.Configuration.ConfigurationManager.AppSettings["IP2"];
                Url = System.Configuration.ConfigurationManager.AppSettings["URL"];
                Port = int.Parse(System.Configuration.ConfigurationManager.AppSettings["Port"].ToString());
                TimeOut = int.Parse(System.Configuration.ConfigurationManager.AppSettings["TimeOut"].ToString());

                //启动网络诊断
                _bIsOpen = false;
                var _thrdNet = new System.Threading.Thread(DoListenNet) { IsBackground = true };
                _thrdNet.Start();
            }
            catch (Exception ex)
            {
                _bIsOpen = false;
                MessageBox.Show("读取本地配置参数出错\r\n" + ex.ToString());
            }
        }


        /// <summary>
        /// 监听网络
        /// </summary>
        private void DoListenNet()
        {
            while (!_bIsOpen)
            {
                DoPingIPStatus();
                System.Threading.Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 网络诊断
        /// </summary>
        private void DoPingIPStatus()
        {
            try
            {
                Ping ping = new Ping();
                PingOptions pingOptions = new PingOptions();
                pingOptions.DontFragment = true;
                string s = "test";
                byte[] bytes = Encoding.ASCII.GetBytes(s);
                int timeout = 120;
                PingReply pingReply = ping.Send(IP1, timeout, bytes, pingOptions);
                if (pingReply != null && pingReply.Status == IPStatus.Success)
                {
                    _bIsOpen = true;
                    //Url = "http://" + IP1 + ":" + Port.ToString();//采用域名，屏蔽ip访问
                }
                else
                {
                    pingReply = ping.Send(IP2, timeout, bytes, pingOptions);
                    if (pingReply != null && pingReply.Status == IPStatus.Success)
                    {
                        _bIsOpen = true;
                        //Url = "http://" + IP2 + ":" + Port.ToString();
                    }
                    else
                    {
                        _bIsOpen = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("网络状态无法监听，无法识别服务器");
            }
        }

        /// <summary>
        /// 系统登录
        /// </summary>
        private void DoLogin()
        {
            var userAccount = txt_UserAccout.Text;
            var userPwd = txt_Pwd.Text;
            if (_isNeedLogin)
            {
                if (string.IsNullOrEmpty(userAccount))
                {
                    MessageBox.Show(@"请输入用户账号!");
                    txt_UserAccout.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(userPwd))
                {
                    MessageBox.Show(@"请输入用户用户密码!");
                    txt_Pwd.Focus();
                    return;
                }

                if (!_bIsOpen)
                {
                    MessageBox.Show("无法连接到服务器，请检查网络设置!");
                    return;
                }

                DataSet ds;

                //调用服务端中间件实现登录功能  返回用户所有权限
                try
                {
                    var msg = new DasMsgExecProc
                    {
                        ProcName = "PCK_UserLogin.LOGINS",
                        ProcParams = new[]
                        {
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Varchar2),
                                Direction = ParameterDirection.Input,
                                Name = "USERNAME",
                                Value = userAccount
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Varchar2),
                                Direction = ParameterDirection.Input,
                                Name = "USERPWD",
                                Value =
                                    BitConverter.ToString(SHA1.Encrypt(Encoding.UTF8.GetBytes(userPwd)))
                                        .Replace("-", "")
                                        .ToLower()
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Varchar2),
                                Direction = ParameterDirection.Input,
                                Name = "USERIP",
                                Value = GetLocalIp()
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Varchar2),
                                Direction = ParameterDirection.Input,
                                Name = "USERMAC",
                                Value = GetLocalMac()
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.RefCursor),
                                Direction = ParameterDirection.Output,
                                Name = "DS",
                                Value = null
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Decimal),
                                Direction = ParameterDirection.Output,
                                Name = "ERRCODE",
                                Value = 0
                            },
                            new ProcParam
                            {
                                DbType = Convert.ToInt32(ODB_Type.Varchar2),
                                Direction = ParameterDirection.Output,
                                Name = "ERRMSG",
                                Value = null,
                                Size = 2000
                            }
                        }
                    };
                    var reqContentPlain = JsonConvert.SerializeObject(msg);
                    //Url = "http://192.168.102.2:10100";
                    var dasClientResult = DasClinet.SendPost(Url + "/Common/ExecProc.do", 30 * 1000, true, userAccount,
                        userPwd, reqContentPlain);
                    if (!dasClientResult.IsSuccess || dasClientResult.StatusCode != 1)
                    {
                        if (dasClientResult.ErrInfo.IndexOf("未经授权", StringComparison.Ordinal) >= 0)
                        {
                            MessageBox.Show(@"登录失败，您无权访问此系统，请与管理员联系！");
                            MessageBox.Show(dasClientResult.ErrInfo);
                        }
                        else
                            MessageBox.Show(@"登录失败，可能是以下原因引起：\n" + @"1. " + dasClientResult.ErrInfo + @"2. " +
                                            dasClientResult.StatusDesc);
                        return;
                    }
                    //反序列响应数据到具体的业务响应实体对象
                    var jsonSet = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                    var jsonRsp = JsonConvert.DeserializeObject<DasMsgExecProc>(dasClientResult.ResponseContentPlain,
                        jsonSet);
                    ds = jsonRsp.ResultDataset;

                    if (jsonRsp.ProcParams[5].Value.ToString() != "0")
                    {
                        MessageBox.Show(@"登录失败，可能是以下原因引起：\n" + @"1. " + jsonRsp.ProcParams[6].Value);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                //CheckClientUpdate(userAccount, userPwd);
                SetUserInfo(userAccount, userPwd, ds);
            }
            else
            {
                DataSet ds = new DataSet();
                System.Data.DataTable dt = new System.Data.DataTable();
                DataColumn dc1 = new DataColumn("ID", typeof(string));
                dt.Columns.Add(dc1);
                DataColumn dc2 = new DataColumn("menuname", typeof(string));
                dt.Columns.Add(dc2);
                DataColumn dc3 = new DataColumn("imageurl", typeof(string));
                dt.Columns.Add(dc3);
                DataColumn dc4 = new DataColumn("navigateurl", typeof(string));
                dt.Columns.Add(dc4);
                DataColumn dc5 = new DataColumn("sortindex", typeof(string));
                dt.Columns.Add(dc5);
                DataColumn dc6 = new DataColumn("parentid", typeof(string));
                dt.Columns.Add(dc6);
                DataColumn dc7 = new DataColumn("UserId", typeof(string));
                dt.Columns.Add(dc7);
                DataColumn dc8 = new DataColumn("roleid", typeof(string));
                dt.Columns.Add(dc8);
                DataColumn dc9 = new DataColumn("rolename", typeof(string));
                dt.Columns.Add(dc9);
                DataColumn dc10 = new DataColumn("CHINESENAME", typeof(string));
                dt.Columns.Add(dc10);

                DataRow dr1 = dt.NewRow();
                dr1["ID"] = "264";
                //dr1["menuname"] = "化验数据管理";//必须修改成与ClientMenuList中一致
                dr1["menuname"] = "入厂验票管理";//必须修改成与ClientMenuList中一致
                dr1["imageurl"] = "~/res/images/menu/basedata.png";
                dr1["navigateurl"] = "";
                dr1["sortindex"] = "1";
                dr1["parentid"] = "";
                dr1["UserId"] = "";
                dr1["roleid"] = "";
                dr1["rolename"] = "";
                dr1["CHINESENAME"] = "";
                dt.Rows.Add(dr1);

                DataRow dr2 = dt.NewRow();
                dr2["ID"] = "265";
                //dr2["menuname"] = "化验数据管理系统";
                dr2["menuname"] = "入厂验票管理系统";
                dr2["imageurl"] = "SampleLablePrint.png";//图片必须有
                //dr2["navigateurl"] = "Titan.FIS.LMS.FrmResultManage";//必须修改成与ClientMenuList中一致
                dr2["navigateurl"] = "Titan.FIS.CRC.frmCarIn";//必须修改成与ClientMenuList中一致              
                dr2["sortindex"] = "11";//菜单排序
                dr2["parentid"] = "264";
                dr2["UserId"] = "";
                dr2["roleid"] = "";
                dr2["rolename"] = "";
                dr2["CHINESENAME"] = "入厂验票管理员";
                dt.Rows.Add(dr2);

                DataRow dr3 = dt.NewRow();
                dr3["ID"] = "266";
                dr3["menuname"] = "入厂车辆查询系统";
                dr3["imageurl"] = "SampleLablePrint.png";//图片必须有
                dr3["navigateurl"] = "Titan.FIS.CRC.frmQueryCRC";//必须修改成与ClientMenuList中一致
                dr3["sortindex"] = "12";
                dr3["parentid"] = "264";
                dr3["UserId"] = "";
                dr3["roleid"] = "";
                dr3["rolename"] = "";
                dr3["CHINESENAME"] = "入厂验票管理员";
                dt.Rows.Add(dr3);

                DataRow dr4 = dt.NewRow();
                dr4["ID"] = "267";
                dr4["menuname"] = "榜单打印系统";
                dr4["imageurl"] = "SampleLablePrint.png";//图片必须有
                dr4["navigateurl"] = "Titan.FIS.CRC.frmQueryBill";//必须修改成与ClientMenuList中一致
                dr4["sortindex"] = "13";
                dr4["parentid"] = "264";
                dr4["UserId"] = "";
                dr4["roleid"] = "";
                dr4["rolename"] = "";
                dr4["CHINESENAME"] = "入厂验票管理员";
                dt.Rows.Add(dr4);

                ds.Tables.Add(dt);
                SetUserInfo(userAccount, userPwd, ds);
            }
            LoadAssemblyInfo();

            LoginLog(userAccount);
            DialogResult = DialogResult.OK;
            Close();
        }

        /// <summary>
        /// 登录日志
        /// </summary>
        /// <param name="userAccount"></param>
        public void LoginLog(string userAccount)
        {
            try
            {
                string SQL = $"INSERT INTO SYSLOG (ID,OPERATOR,MESSAGE,TYPE,RESULT,MODULE,CREATETIME)VALUES('{NewId}','{userAccount}','登录成功','登录','成功','桌面系统',SYSDATE)";
                DataHelper.Instance.ExecSql("interface", "Admin123", SQL);
            }
            catch
            {
            }
        }

        public static string NewId
        {
            get
            {
                string id = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                string guid = Guid.NewGuid().ToString().Replace("-", "");
                id += guid.Substring(0, 10);
                return id;
            }
        }

        private void CheckClientUpdate(string userName, string userPwd)
        {
            try
            {
                //发送GET请求获得响应数据
                var dasClientResult = DasClinet.SendGet(Url + "/ClientUpdate/Check.do", 30 * 1000, true, userName, userPwd);
                if (!dasClientResult.IsSuccess || dasClientResult.StatusCode != 1)
                {
                    MessageBox.Show(@"检查更新失败：" + dasClientResult.ErrInfo);
                    return;
                }

                var jsonSet = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };
                //反序列响应数据到具体的业务响应实体对象      
                var jsonVersionRsp = JsonConvert.DeserializeObject<ClinetUpdate.DasRspMsgClientUpdateCheck>(dasClientResult.ResponseContentPlain, jsonSet);
                if (jsonVersionRsp.VersionNum <= _version) return;
                ultraProgressBar1.Visible = true;//有更新时显示进度条
                var iCount = jsonVersionRsp.PatchFiles.Count;//总文件数
                var kCount = 0;
                foreach (var patchFile in jsonVersionRsp.PatchFiles)
                {
                    kCount++;
                    dasClientResult = DasClinet.SendGet(Url + "/ClientUpdate/Download.do?file=" + patchFile.FileName, 30 * 1000, true, userName, userPwd);
                    if (!dasClientResult.IsSuccess || dasClientResult.StatusCode != 1)
                    {
                        MessageBox.Show(@"获取服务端文件失败：" + dasClientResult.ErrInfo);
                        return;
                    }

                    var jsonFile = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                    //反序列响应数据到具体的业务响应实体对象
                    var jsonFileRsp = JsonConvert.DeserializeObject<ClinetUpdate.DasRspMsgClientUpdateDownload>(dasClientResult.ResponseContentPlain, jsonFile);

                    //检查MD5
                    var md5 = BitConverter.ToString(MD5.Encrypt(jsonFileRsp.FileContent)).Replace("-", "").ToLower();
                    if (string.Compare(md5, jsonFileRsp.FileMD5, StringComparison.OrdinalIgnoreCase) != 0)
                    {
                        MessageBox.Show(@"下载的补丁文件MD5校验无效");
                        return;
                    }

                    //写入文件
                    using (
                        var fs =
                            new FileStream(
                                Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                    jsonFileRsp.FileName.Replace("/", "\\").Trim('\\')), FileMode.Create,
                                FileAccess.Write, FileShare.ReadWrite))
                    {
                        fs.Write(jsonFileRsp.FileContent, 0, jsonFileRsp.FileContent.Length);
                    }
                    ultraProgressBar1.Value = kCount / iCount * 100;
                    Application.DoEvents();
                }
                //更新完成写注册表版本号
                WriteVersion(jsonVersionRsp.VersionNum);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 保存版本号信息
        /// </summary>
        /// <param name="iVersion"></param>
        private void WriteVersion(int iVersion)
        {
            var map = new ExeConfigurationFileMap { ExeConfigFilename = "Titan.WinFormSys.exe.Config" };
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            config.AppSettings.Settings["Version"].Value = iVersion.ToString();
            config.Save();
        }

        private void SetUserInfo(string strUserName, string strUserPwd, DataSet ds)
        {
            var powerList = new List<RolePowersEntity>();
            var strUid = "";
            var strRoleId = "";
            var strRoleName = "";
            var chinesename = "";
            if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)
            {
                FrmBase.UserInfo = new UserInfoEntity(strUid, strUserName, strUserPwd, strRoleId, strRoleName, _localIP, _localMAC, chinesename, powerList);
                return;
            }
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                var strId = row["ID"].ToString();
                var strName = row["menuname"].ToString();
                var strImageUrl = row["imageurl"].ToString();
                var strNavigateUrl = row["navigateurl"].ToString();
                var iIndex = Convert.ToInt32(row["sortindex"].ToString());
                var strParentId = row["parentid"].ToString();
                var strKeyCode = row["KeyCode"].ToString();
                strUid = row["UserId"].ToString();
                strRoleId = row["roleid"].ToString();
                strRoleName = row["rolename"].ToString();
                chinesename = row["CHINESENAME"].ToString();
                powerList.Add(new RolePowersEntity(strId, strName, strImageUrl, strNavigateUrl, iIndex, strParentId, strKeyCode));
            }
            FrmBase.UserInfo = new UserInfoEntity(strUid, strUserName, strUserPwd, strRoleId, strRoleName, _localIP, _localMAC, chinesename, powerList);
        }

        private string GetLocalIp()
        {
            try
            {
                //获取本机活动网卡IP 优先有线网卡
                System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                c.Connect(IP1, 80);
                string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                c.Close();
                _localIP = ip;
                return _localIP;

                ////获取公网IP
                //var webClient = new WebClient();
                //webClient.Credentials = CredentialCache.DefaultCredentials;
                //byte[] pageDate = webClient.DownloadData("http://pv.sohu.com/cityjson?ie=utf-8");
                //String ip = Encoding.UTF8.GetString(pageDate);
                //webClient.Dispose();
                //Match rebool = Regex.Match(ip, @"\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");
                //return rebool.Value;
            }
            catch (Exception)
            {
                return "127.0.0.1";
            }
            //var hostname = Dns.GetHostName(); //得到本机名   
            //var localhost = Dns.GetHostEntry(hostname);
            //foreach (IPAddress localAddress in localhost.AddressList)
            //{
            //    if (localAddress.AddressFamily == AddressFamily.InterNetwork)
            //    {
            //        返回第一个IP4的地址
            //        return localAddress.ToString();
            //    }
            //}
            //return "127.0.0.1";
        }

        private string GetLocalMac()
        {
            var interfaces = NetworkInterface.GetAllNetworkInterfaces();
            var strMac = interfaces.Where(ni => ni.OperationalStatus == OperationalStatus.Up).Aggregate("", (current, ni) => current + (ni.GetPhysicalAddress().ToString() + "|"));
            _localMAC = strMac.Split('|')[0];
            return _localMAC;
        }

        /// <summary>
        /// 加载DLL信息
        /// </summary>
        private void LoadAssemblyInfo()
        {
            var filePath = Environment.CurrentDirectory + @"\ClientFileList.xml";
            if (!File.Exists(filePath)) return;

            if (AssemblyEntity.AssemblyHt != null)
                AssemblyEntity.AssemblyHt.Clear();
            if (AssemblyEntity.FormHt != null)
                AssemblyEntity.FormHt.Clear();

            if (File.Exists(filePath))
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);
                var xn = xmlDoc.SelectSingleNode("Files");
                if (xn == null) return;
                var xnl = xn.ChildNodes;
                foreach (var strAssemblyName in from XmlNode cxn in xnl
                                                let xmlAttributeCollection = cxn.Attributes
                                                where xmlAttributeCollection != null
                                                where xmlAttributeCollection != null
                                                select xmlAttributeCollection["fileName"].Value.ToUpper())
                {
                    var strAssName = "";
                    if (strAssemblyName.IndexOf(".DLL", StringComparison.Ordinal) > 0)
                        strAssName = strAssemblyName.Substring(0, strAssemblyName.IndexOf(".DLL", StringComparison.Ordinal));
                    if (strAssemblyName.IndexOf(".EXE", StringComparison.Ordinal) > 0)
                        strAssName = strAssemblyName.Substring(0, strAssemblyName.IndexOf(".EXE", StringComparison.Ordinal));
                    if (AssemblyEntity.AssemblyHt != null && !string.IsNullOrEmpty(strAssName))
                        AssemblyEntity.AssemblyHt.Add(strAssName, LoadAssembly(strAssName));
                }
            }
            else MessageBox.Show(@"未找到需要加载的DLL文件");
        }

        /// <summary>
        /// 加载DLL信息
        /// </summary>
        /// <param name="strAssemblyName">程序集名称</param>
        private Assembly LoadAssembly(string strAssemblyName)
        {
            return Assembly.Load(strAssemblyName);
        }

        private void txt_Pwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) DoLogin();
        }

        private void txt_UserAccout_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) txt_Pwd.Focus();
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            var str = ReadFile(FilePath, Encoding.UTF8);
            if (string.IsNullOrEmpty(str)) return;
            var userArray = str.Split(Convert.ToChar(";"));
            foreach (var s in userArray)
            {
                var newdr = dataTable1.NewRow();
                newdr["allName"] = s.Replace("\r\n", "");
                dataTable1.Rows.Add(newdr);
            }
            txt_UserAccout.Focus();

        }


        /// <summary>
        /// 读取指定文件内容
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="encodingType">编码类型</param>
        /// <returns>正常读取返回文件内容，发生异常时返回null</returns>
        public string ReadFile(string fileName, Encoding encodingType)
        {
            string content;//返回的字符串
            // 以只读模式打开一个文本文件
            if (!File.Exists(fileName)) return "";
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                using (var reader = new StreamReader(fs, encodingType))
                {
                    content = reader.ReadToEnd();
                }
            }
            return content;
        }

        /// <summary>
        /// 写入指定文件 创建新文件。如果文件已存在，它将被覆盖
        /// </summary>
        /// <param name="filePath">文件地址</param>
        /// <param name="strContent">要写入的值</param>
        /// <param name="encodingType">编码类型</param>
        ///<returns>返回True在结果为成功，False反之</returns>
        public void WriteFile(string filePath, string strContent, Encoding encodingType)
        {
            using (var fst = new FileStream(filePath, FileMode.Append))
            {
                using (var swt = new StreamWriter(fst, encodingType))
                {
                    swt.WriteLine(strContent);
                    swt.Close();
                    fst.Close();
                }
            }
        }

        /// <summary>  
        /// 十进制数据byte转换为BCD码
        /// </summary>  
        /// <param name="b" />十进制数据  
        /// <returns>返回转换后的BCD码</returns>  
        public byte ConvertIntToBcd(byte b)
        {
            //高四位  
            byte b1 = (byte)(b / 10);
            //低四位  
            byte b2 = (byte)(b % 10);
            return (byte)((b1 << 4) | b2);
        }

        /// <summary>  
        /// 将BCD一字节数据转换到byte十进制数据  
        /// </summary>  
        /// <param name="b" />BCDD码  
        /// <returns>返回转换后的十进制数据</returns>  
        public static byte ConvertBcdToInt(byte b)
        {
            //高四位  
            byte b1 = (byte)((b >> 4) & 0xF);
            //低四位  
            byte b2 = (byte)(b & 0xF);
            return (byte)(b1 * 10 + b2);
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //string aa = Titan.FIS.BatchCodeEncode.Helper.Encode("12345678");
            //string bb = Titan.FIS.BatchCodeEncode.Helper.Decode("83c556343683");
            //string aa1 = Titan.FIS.BatchCodeEncode.Helper.Encode("21031702");
            //var ss = System.Text.Encoding.UTF8.GetBytes(aa1);
            //string bb1 = Titan.FIS.BatchCodeEncode.Helper.Decode(aa1);
            //string aa2 = Titan.FIS.BatchCodeEncode.Helper.Encode("21012103");
            //string bb2 = Titan.FIS.BatchCodeEncode.Helper.Decode(aa2);
            //string test = Titan.FIS.BatchCodeEncode.Helper.Decode("527335794f");
            //var strContent = string.Empty;
            //var byteContent = new byte[8];
            //byteContent[0] = ConvertIntToBcd(20);
            //byteContent[1] = ConvertIntToBcd((byte)(DateTime.Now.Year - 2000));
            //byteContent[2] = ConvertIntToBcd((byte)(DateTime.Now.Month));
            //byteContent[3] = ConvertIntToBcd((byte)(DateTime.Now.Day));
            //byteContent[4] = ConvertIntToBcd((byte)(DateTime.Now.Hour));
            //byteContent[5] = ConvertIntToBcd((byte)(DateTime.Now.Minute));
            //byteContent[6] = ConvertIntToBcd((byte)(DateTime.Now.Second));
            //byteContent[7] = ConvertIntToBcd(62);

            //for (int i = 0; i < 8; i++)
            //{
            //    strContent += ConvertBcdToInt(byteContent[i]).ToString("D2") +  " ";
            //}
            //strContent = strContent.Trim();

            DoLogin();
        }



        private void btnLayout_Click(object sender, EventArgs e)
        {
            Dispose();
            Application.ExitThread();
            Application.Exit();
        }


        private void panel1_Click(object sender, EventArgs e)
        {
            Dispose();
            Application.ExitThread();
            Application.Exit();
        }






    }
}
